package br.ufrj.dcc.tp.client;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

import javax.swing.JOptionPane;

import br.ufrj.dcc.tp.common.Client;
import br.ufrj.dcc.tp.common.Message;

public class ClientService {

	private static ClientService service;
	private Client client;
	private Socket socket;
	private MainView view;
	
	private ClientService() {
		view = ClientFactory.getMainViewInstance();
		initializeSendMessageEvents();
		String name = JOptionPane.showInputDialog("What's your name?");
		
		view.setVisible(true);
		
		String host = "127.0.0.1";
		
		try {
			
            socket = new Socket(host, 3702);
            client = new Client(name);
            
            Thread t = new ClientThreadMessageReceiver(client,socket);
            t.start();
            
            
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: " + host);
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for "
                               + "the connection to: " + host);
            System.exit(1);
        }
	}
	
	public static ClientService getInstance() {
		if (service == null) service = new ClientService();
		return service;
	}
	
	/**
	 * Envia mensagem ao servidor ao clicar no botão bem como pressionando a 
	 * tecla ENTER
	 * @message mensagem a ser enviada
	 * */
	public void initializeSendMessageEvents() {
		
		view.getSendMessagutton().addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				sendMessage();
			}
		});
		
		view.getTxtMessage().addKeyListener(new KeyAdapter() {
			
			@Override
			public void keyReleased(KeyEvent e) {
				if (e.getKeyCode() == KeyEvent.VK_ENTER) {
		            sendMessage();
		        }
			}

		});
	}
	
	
	private void sendMessage() {
		String message = view.getTxtMessage().getText();
		
		Message msg = new Message(client, new Date(), message);
		try {
			ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
			out.writeObject(msg);
			out.flush();
			
			view.getTxtMessage().setText("");
		} catch (IOException ex) {
			System.out.println("[ClientService] Failed to send message object {" + msg + "}");
			
		}
	}
	
	/**
	 * Atualiza a lista de usuários online
	 * */
	public void updateList(Set<String> clients) {
		view.getListClients().setListData(clients.toArray());
	}
	
	
	/**
	 * Fecha todas as conexões ao fechar a janela.
	 * */
	public void closeConnection() {
		try {
			//out.close();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	
}
